<template>
  <div class="change-password-page">
    <van-nav-bar
        title="修改密码"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
    />

    <van-form @submit="onSubmit" class="password-form">
      <van-cell-group inset>
        <!-- 原密码 -->
        <van-field
            v-model="form.oldPassword"
            type="password"
            name="oldPassword"
            label="原密码"
            placeholder="请输入原密码"
            :rules="[{ required: true, message: '请填写原密码' }]"
        />

        <!-- 新密码 -->
        <van-field
            v-model="form.newPassword"
            type="password"
            name="newPassword"
            label="新密码"
            placeholder="请输入新密码"
            :rules="[
            { required: true, message: '请填写新密码' },
            { validator: validatePassword, message: '密码需6-20位字母数字组合' }
          ]"
        />

        <!-- 确认密码 -->
        <van-field
            v-model="form.confirmPassword"
            type="password"
            name="confirmPassword"
            label="确认密码"
            placeholder="请再次输入新密码"
            :rules="[
            { required: true, message: '请再次输入新密码' },
            { validator: validateConfirmPassword, message: '两次输入密码不一致' }
          ]"
        />
      </van-cell-group>

      <div style="margin: 16px;">
        <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
        >
          确认修改
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import {ref} from 'vue'
import {showSuccessToast, showFailToast} from 'vant'
import {useRouter} from 'vue-router'
import {resetPasswordAPI} from "@/api/auth";

const router = useRouter()

// 表单数据
const form = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 加载状态
const loading = ref(false)

// 密码校验规则
const validatePassword = (val: string) => {
  return /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/.test(val)
}

// 确认密码校验
const validateConfirmPassword = (val: string) => {
  return val === form.value.newPassword
}

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 提交表单
const onSubmit = async () => {
  try {
    loading.value = true
    const {data} = await resetPasswordAPI({
      oldPassword: form.value.oldPassword,
      newPassword: form.value.newPassword
    })
    if (data){
      showSuccessToast('密码修改成功')
      router.back()
    }
  } catch (error: any) {
    showFailToast(error || '密码修改失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.change-password-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.password-form {
  margin-top: 20px;
}
</style>
